#!/usr/bin/bash

    TMP_DIR=$(dirname $(mktemp -u))
    TMP=$TMP_DIR/change_background
    rm -r $TMP 2>/dev/null; mkdir $TMP
    sudo echo

login_background_theme() {
  local GST=/usr/share/gnome-shell/gnome-shell-theme.gresource
  local GSTRES=$(basename $GST)
  local WORKDIR=${TMP}/gdm-login-background

  if [ -f ${GST}.backup ]; then
    sudo mv ${GST}.backup ${GST}
  fi
 
  mkdir -p $WORKDIR
  cd $WORKDIR
  mkdir -p theme

for r in $(gresource list $GST); do
    t="${r/#\/org\/gnome\/shell\/}"
    mkdir -p $(dirname $t)
    gresource extract $GST $r >$t
done

  cd theme
  cp "$IMAGE" ./
  sync
  IMAGE=$(basename $IMAGE)

  cat gnome-shell.css | \
  sed -e 's/#lockDialogGroup/#lockDialogGroup-ignore/g' >gnome-shell.tmp

  echo "
#lockDialogGroup {
  background: #2e3436 url(resource:///org/gnome/shell/theme/${IMAGE});
  background-repeat: no-repeat;
  background-size: cover; }" >>gnome-shell.tmp

  sync
  mv gnome-shell.tmp gnome-shell.css

  echo '<?xml version="1.0" encoding="UTF-8"?>
<gresources>
  <gresource prefix="/org/gnome/shell/theme">' >"${GSTRES}.xml"
  for r in `ls *.*`; do
    echo "    <file>$r</file>" >>"${GSTRES}.xml"
  done
  echo '  </gresource>
</gresources>' >>"${GSTRES}.xml"
  sync
  glib-compile-resources "${GSTRES}.xml"

  sudo mv "/usr/share/gnome-shell/$GSTRES" \
  "/usr/share/gnome-shell/${GSTRES}.backup"

  sudo mv "$GSTRES" /usr/share/gnome-shell/
}

no_selected_image_file() {
    IMAGE_FILE=$(
      dbus-launch gsettings get org.gnome.desktop.background picture-uri |
      sed -e "s/'//g" |
      sed -e "s|^file:///||g"
    )
  if [ -f $IMAGE_FILE ]; then
      echo $IMAGE_FILE
  else
    exit 1
  fi
}
create_blur_effect() {
  if [[ $BLUR -gt 0 && $BLUR -le 100 ]]; then
    if type convert &>/dev/null; then
	convert -blur 0x$BLUR $IMAGE_FILE $TMP/gdm_login.$FRM
    else
	cp $IMAGE_FILE $TMP/gdm_login.$FRM
    fi
  else
    cp $IMAGE_FILE $TMP/gdm_login.$FRM
  fi

}

selected_image_file() {
  if [[ -n $IMAGE_FILE && -f $IMAGE_FILE ]]; then
    if grep -qi 'JPEG\|PNG' <<<$(file $IMAGE_FILE); then
        IMAGE_FILE=$IMAGE_FILE
    else
        IMAGE_FILE=$(no_selected_image_file)
    fi
  else
    IMAGE_FILE=$(no_selected_image_file)
  fi
    FRM=$(rev <<<$IMAGE_FILE|cut -d. -f1|rev)
}

  command_line=$(tr ' ' '\n' <<<$@)
    if grep -q '^/' <<<"$command_line"; then
	IMAGE_FILE=$(grep '^/'<<< "$command_line")
    fi
	selected_image_file
    if grep -q '\-b\=' <<<"$command_line"; then
	BLUR=$(grep '\-b\='<<< "$command_line"|cut -d= -f2)
	create_blur_effect
    else
	cp $IMAGE_FILE $TMP/gdm_login.$FRM
    fi
	IMAGE="$TMP/gdm_login.$FRM"
	
    if grep -q '\-k' <<<"$command_line"; then
	sudo cp $IMAGE /usr/share/backgrounds/
	gsettings set org.gnome.desktop.screensaver picture-uri \
	"file:///usr/share/backgrounds/gdm_login.$FRM"
    fi
    if [[ $(sudo whoami) == root ]]; then
		login_background_theme
    fi
